/*
 * FaceAnalyzer.cpp
 *
 *  Created on: 2018年9月4日
 *      Author: zhengboyuan
 */

#include "FaceAnalyzer.h"
#include "TStringUtil.h"

#ifndef TRUE
#define TRUE                1
#endif

void FaceAnalyzer::decodeCallback(HANDLE handle, MDecode_Frame* frame, void* pUser)
{
	FaceAnalyzer* pthis = (FaceAnalyzer*)pUser;
	pthis->onDecodeFrame(handle, frame);
}

FaceAnalyzer::FaceAnalyzer():
	m_handle(),
	m_sink(),
	m_frameCount()
{
}

FaceAnalyzer::~FaceAnalyzer()
{
	close();
}

bool FaceAnalyzer::open(const MDecode_Format& fmt)
{
	m_handle = MDecode_CreateHandle();
	BOOL ret = MDecode_OpenStream(m_handle, &fmt);

	MDecode_SetDecodeCallback(m_handle, MDECODE_PIXEL_I420, FaceAnalyzer::decodeCallback, this);

	MDecode_SetDecodeCallbackFreq(m_handle, 30);

	MDecode_Play(m_handle);

	return (ret == TRUE);
}

void FaceAnalyzer::close()
{
	if (m_handle)
	{
		MDecode_CloseStream(m_handle);
		MDecode_DestroyHandle(m_handle);
		m_handle = 0;
	}
}

void FaceAnalyzer::input(int mediaType, const uint8_t* buffer, int length, int64_t pts, int flags)
{
	MDecode_InputData(m_handle, mediaType, buffer, length, pts, flags);
}

void FaceAnalyzer::setSink(FaceAnalyzerSink* sink)
{
	m_sink = sink;
}

void FaceAnalyzer::onDecodeFrame(HANDLE handle, MDecode_Frame* frame)
{
	//printf("frame. width: %d, height: %d, pts: %lld\n", frame->width, frame->height, frame->pts);
	
	m_frameCount++;
	std::string text = makeFaceTrack(frame->pts);

	if (m_sink)
	{
		m_sink->onFace(text, frame->pts);
	}
}


std::string FaceAnalyzer::makeFaceTrack(int64_t pts)
{
	int gender = m_frameCount % 2;
	int age = (m_frameCount + 1) % 2;

	int xStep = (m_frameCount % 16) * 10;
	int yStep = (m_frameCount % 9) * 10;

	int x1 = 50 + xStep;
	int y1 = 50 + yStep;
	int x2 = 200 + xStep;
	int y2 = 200 + yStep;

	int rx = 40 + xStep;
	int ry = 40 + yStep;

	std::string text = comn::StringUtil::format(
		"{\"channel_id\":\"2200001201000501\",\"frame_id\":\"%lld\",\"line_color\":\"0000FF\",\"line_size\":2,\"font_size\":20,\"font_type\":0,\"font_color\":\"FF0000\",\"face_rec\":[{\"x1\":%d,\"y1\":%d,\"x2\":%d,\"y2\":%d,\"remark\":\"%d/%d/1\",\"remark_pointX\":%d,\"remark_pointY\":%d}, {\"x1\":400,\"y1\":200,\"x2\":500,\"y2\":400,\"remark\":\"1/1/2\",\"remark_pointX\":400,\"remark_pointY\":160}]}",
		pts, x1, y1, x2, y2,
		gender, age,
		rx, ry
		);

	return text;
}
